/******************************************************************************
	Cobalt - utility libraries for building XNA games
	Copyright (C) 2008 Philip Djonov

	This program is free software; you can redistribute it and/or modify it
	under the terms of the GNU General Public License as published by the Free
	Software Foundation; either version 2 of the License, or (at your option)
	any later version.

	This program is distributed in the hope that it will be useful, but
	WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
	or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
	for more details.

	You should have received a copy of the GNU General Public License along
	with this program; if not, write to the
	
		Free Software Foundation, Inc.
		51 Franklin Street, Fifth Floor
		Boston, MA  02110-1301, USA.
******************************************************************************/

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Cobalt.Framework.Graphics.Content
{
	internal sealed class StaticGeometryReader : ContentTypeReader<StaticGeometry>
	{
		protected override StaticGeometry Read( ContentReader input, StaticGeometry existingInstance )
		{
			Material[] materials = new Material[input.ReadInt32()];
			for( int i = 0; i < materials.Length; i++ )
				materials[i] = input.ReadObject<Material>();

			List<StaticGeometrySurface> surfaces = new List<StaticGeometrySurface>();

			StaticGeometryBuffer[] buffers = new StaticGeometryBuffer[input.ReadInt32()];
			for( int i = 0; i < buffers.Length; i++ )
			{
				StaticGeometryBuffer buf = new StaticGeometryBuffer();

				buf.VertexBuffer = input.ReadObject<VertexBuffer>();
				buf.VertexDeclaration = input.ReadObject<VertexDeclaration>();
				buf.IndexBuffer = input.ReadObject<IndexBuffer>();

				buf.VertexStride = buf.VertexDeclaration.GetVertexStrideSize( 0 );

				int surfCount = input.ReadInt32();
				for( int j = 0; j < surfCount; j++ )
				{
					StaticGeometrySurface surf = new StaticGeometrySurface( buf );

					surf.Material = materials[input.ReadInt32()];
					
					BoundingSphere bounds = input.ReadRawObject<BoundingSphere>();
					surf.center = bounds.Center;
					surf.BoundingRadius = bounds.Radius;

					surf.FirstVertex = input.ReadInt32();
					surf.VertexCount = input.ReadInt32();
					surf.FirstIndex = input.ReadInt32();
					surf.PrimitiveCount = input.ReadInt32();

					surf.surfaceSort = j;

					surfaces.Add( surf );
				}

				buffers[i] = buf;
			}

			StaticGeometry ret = new StaticGeometry();

			ret.Buffers = buffers;
			ret.Surfaces = surfaces.ToArray();
			
			return ret;
		}
	}
}
